package com.efast.cafe.framework.controller;


import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.efast.cafe.framework.bean.QueryPageBase;
import com.efast.cafe.framework.bean.ResultBean;
import com.efast.cafe.framework.convert.MyCustomDateEditor;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.pager.Pagination;
import com.efast.cafe.framework.vo.DataTableVo;



public abstract class AbstractController {
	
	private final Logger log = LoggerFactory.getLogger(getClass());
	private static String key = "and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+";
    private static Set<String> notAllowedKeyWords = new HashSet<String>(0);
    private static String replacedString="INVALID";
    static {
        String keyStr[] = key.split("\\|");
        for (String str : keyStr) {
            notAllowedKeyWords.add(str);
        }
    }
	protected final String SUCCESS="success";
	protected final String FAILURE="failure";
	protected final String SAVE_SUCCESS_TIP = "common.msg.save.success";
	protected final String SAVE_FAILURE_TIP = "common.msg.save.error";
	protected final String ADD_SUCCESS_TIP = "common.msg.add.success";
	protected final String ADD_FAILURE_TIP = "common.msg.add.failure";
	protected final String EDIT_SUCCESS_TIP = "common.msg.edit.success";
	protected final String EDIT_FAILURE_TIP = "common.msg.edit.error";
	protected final String DEL_SUCCESS_TIP = "common.msg.delete.success";
	protected final String DEL_FAILURE_TIP = "common.msg.delete.field";
	protected final String SEND_SUCCESS_TIP = "common.msg.sendEmail.success";
	protected final String SEND_FAILURE_TIP = "common.msg.sendEmail.field";
	protected final String CHECKED_SUCCESS_TIP = "common.msg.checked.success";
	protected final String CHECKED_FAILURE_TIP = "common.msg.checked.field";
	protected final String IMPROVEDVERSION_SUCCESS_TIP = "common.msg.improvedversion.success";
	protected final String IMPROVEDVERSION_FAILURE_TIP = "common.msg.improvedversion.field";
	protected final String NEXT_RFQ_SUCCESS_TIP = "common.msg.nextRfq.success";
	protected final String NEXT_RFQ_FAILURE_TIP = "common.msg.nextRfq.field";
	protected final String NOMINATION_SUCCESS_TIP = "common.msg.Nomination.success";
	protected final String NOMINATION_FAILURE_TIP = "common.msg.Nomination.field"; 
	protected final String REJECT_SUCCESS_TIP = "common.msg.reject.success";
	protected final String REJECT_FAILURE_TIP = "common.msg.reject.field";
	protected final String STOP_SUCCESS_TIP = "common.msg.stop.success";
	protected final String STOP_FAILURE_TIP = "common.msg.stop.field";
	protected final String FORWARD_SUCCESS_TIP = "common.msg.forward.success";
	protected final String FORWARD_FAILURE_TIP = "common.msg.forward.field";
	protected final String ADD="add";
	protected final String DELETE="del";
	protected final String UPDATE="upd";
	protected final String SEARCH="search";
	
	
	public <T> Pagination<T> initPager(Integer page,Integer rows,String sidx,String sord){
		Pagination<T> pager = new Pagination<T>();
		pager.setCurrentPage(null!=page?page:1);
		pager.setNumPerPage(null!=rows?rows:10);
		pager.setOrderBy(StringUtils.isNotBlank(sidx)?sidx:null);
		pager.setSort(StringUtils.isNotBlank(sord)?sord:null);
		return pager;
	}
	
	@InitBinder    
	public void initBinder(WebDataBinder binder) {    
	    binder.registerCustomEditor(Date.class, new MyCustomDateEditor());    
	}  
	
	
	public String tipJson(int id,String type){
		return tipJson(id,type,null);
	}
	public ResultBean tipResultBean(int id,String type){
		return tipResultBean(id,type,null);
	}
	public ResultBean tipResultBean(int id,String type,Object parameter){
		ResultBean bean = new ResultBean();
		String failureKey="";
		String successKey="";
		if(ADD.equals(type)){
			failureKey=ADD_FAILURE_TIP;
			successKey=ADD_SUCCESS_TIP;
		}else if(UPDATE.equals(type)){
			failureKey=EDIT_FAILURE_TIP;
			successKey=EDIT_SUCCESS_TIP;
		}else if(DELETE.equals(type)){
			failureKey=DEL_FAILURE_TIP;
			successKey=DEL_SUCCESS_TIP;
		}
		bean.setObject(parameter);
		if(id>=1){
			bean.setMessage(successKey);
			bean.setSuccess(true);
			return bean;
		} else {
			bean.setMessage(failureKey);
			bean.setSuccess(false);
		}
		return bean;
	}
	public String tipJson(int id,String type,Object parameter){
		String failureKey="";
		String successKey="";
		if(ADD.equals(type)){
			failureKey=ADD_FAILURE_TIP;
			successKey=ADD_SUCCESS_TIP;
		}else if(UPDATE.equals(type)){
			failureKey=EDIT_FAILURE_TIP;
			successKey=EDIT_SUCCESS_TIP;
		}else if(DELETE.equals(type)){
			failureKey=DEL_FAILURE_TIP;
			successKey=DEL_SUCCESS_TIP;
		}
		return tipJson(id,successKey,failureKey,parameter);
	}
	public String tipJson(int id,String successKey,String failureKey,Object parameter){
		String json = "";
		if (parameter != null) {
			json = ",\"id\":\""+parameter+"\"";
		}
		if(id>=1){	
			return "{\"success\":true"+json+",\"message\":\""+successKey+"\"}";
		}
		return "{\"success\":false"+json+",\"message\":\""+failureKey+"\"}";
	}
	
	
	public <T> DataTableVo<T> outPageJSONArray_bootstrapDatatable(Pagination<T> pager){
		DataTableVo<T> res = new DataTableVo<T>();
		res.setAaData(pager.getResultList());
		res.setRecordsDisplay(pager.getResultList().size());
		res.setRecordsTotal(pager.getTotalRows());
		res.setRecordsFiltered(pager.getTotalRows());
		return res;
	}
	public <T> DataTableVo<T> outPageJSONArray_bootstrapDatatable(QueryPageBase page){
		DataTableVo<T> res = new DataTableVo<T>();
		List rest = page.getResultList();
		List<T> rt = (List<T>)rest;
		res.setAaData(rt);
		res.setRecordsDisplay(rt.size());
		res.setRecordsTotal(page.getTotalRows());
		res.setRecordsFiltered(page.getTotalRows());
		return res;
	}
	
	
	
	protected Map<String,Object> makeReadonly(Map<String,Object> field){
		field.put("readonly", true);
		return field;
	}

	public String cleanXSS(String valueP) {
        // You'll need to remove the spaces from the html entities below
        String value = valueP.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
        value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
        value = value.replaceAll("'", "& #39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
        value = value.replaceAll("script", "");
        value = cleanSqlKeyWords(value);
        return value;
    }
	
	private String cleanSqlKeyWords(String value) {
        String paramValue = value;
        for (String keyword : notAllowedKeyWords) {
            if ((paramValue.contains(" "+keyword)||paramValue.contains(keyword+" ")||paramValue.contains(" "+keyword+" "))) {
                paramValue = StringUtils.replace(paramValue, keyword, replacedString);
                log.error( "已被过滤，因为参数中包含不允许sql的关键词(" + keyword
                        + ")"+";参数："+value+";过滤后的参数："+paramValue);
                throw new ServiceException("参数中包含了非法关键字。");
            }
        }
        return paramValue;
    }
	
}